
const jwt = require('../utils/jwt');
const userModel = require('../model/user');

const login = async (ctx, next) => {
  
  var
  userName = ctx.request.body.userName || '',
  psd = ctx.request.body.psd || '';
  const user = await userModel.findOne({ where: { userName: userName } });
  console.log(`signin with name: ${userName}, password: ${psd}`);
  if (user === null) {
    ctx.send({
      msg: '账号错误',
      resultCode: 0,
    })
  } else {
    if(user.psd === psd){
      let token = jwt.setToken(ctx.request.body)
      ctx.send({
        data: {
          token: token
        },
        resultCode: 1,
        state: 200,
        type: 'success' // 自定义响应体
      })
    }else{
      ctx.send({
        msg: '密码错误',
        resultCode: 0,
      })
    }
  }
};

const logout = async (ctx, next) => {
  // console.log(`signout with `, ctx.request.headers);
  ctx.response.body = {
        data: {
  
        },
        resultCode: 1,
        state: 200,
        type: 'success' // 自定义响应体
      }
  // var
  // userName = ctx.request.body.userName || '',
  // psd = ctx.request.body.psd || '';
  // console.log(`signin with name: ${userName}, password: ${psd}`);
  // if (userName === 'admin' && psd === 'admin') {
  //   ctx.response.body = {
  //     data: {

  //     },
  //     resultCode: 1,
  //     state: 200,
  //     type: 'success' // 自定义响应体
  //   }
  //     // ctx.response.body = `<h1>Welcome, ${userName}!</h1>`;
  // } else {
  //     ctx.response.body = `<h1>Login failed!</h1>
  //     <p><a href="/">Try again</a></p>`;
  // }
};

module.exports = {
  'POST /login': login,
  'POST TOKEN /logout': logout
};